package com.tm.service;

import java.math.BigDecimal;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.tm.ResultEntity;
import com.tm.mapper.CommonMapper;
import com.tm.mapper.EcIncomeDetailMapper;
import com.tm.mapper.EcMemberInfoMapper;
import com.tm.mapper.SpLimitTimeShopMapper;
import com.tm.mapper.SpOrderMapper;
import com.tm.mapper.SpOrderSkuMapper;
import com.tm.mapper.SpSkuInfoMapper;
import com.tm.mapper.SpSpellGroupMapper;
import com.tm.mapper.SpSpellGroupParticipateMapper;
import com.tm.model.EcIncomeDetail;
import com.tm.model.EcMemberInfo;
import com.tm.model.SpLimitTimeShop;
import com.tm.model.SpOrder;
import com.tm.model.SpOrderCriteria;
import com.tm.model.SpOrderSku;
import com.tm.model.SpOrderSkuCriteria;
import com.tm.model.SpSkuInfo;
import com.tm.model.SpSpellGroup;
import com.tm.model.SpSpellGroupParticipate;
import com.tm.pay.config.WechatConfig2;
import com.tm.util.CommonUtilsEx;
import com.tm.util.DateUtilsEx;
import com.tm.util.Md5;
import com.tm.util.SignatureUtil;
import com.tm.util.StringUtilsEx;
import com.tm.util.WXPayUtil;

/**
 * 订单接口服务类
 * @author GXL
 * 2018年3月19日
 * TODO
 */
@Service
public class OrderService {
	
	@Autowired
	private SpOrderMapper soMapper;
	
	@Autowired
	private SpSkuInfoMapper ssiMapper;
	
	@Autowired
	private EcMemberInfoMapper emiMapper;
	
	@Autowired
	private SpOrderSkuMapper sosMapper;
	
	@Autowired
	private SpSpellGroupParticipateMapper ssgpMapper;
	
	@Autowired
	private SpSpellGroupMapper ssgMapper;
	
	@Autowired
	private SpLimitTimeShopMapper sltsMapper;
	
	@Autowired
	private CommonMapper cMapper;
	
	@Autowired
	private EcIncomeDetailMapper eidMapper;

	
	/**
	 *	支付成功，更新订单状态，计算订单分润
	 * @param trade_no 订单号
	 * @param money 实际支付金额
	 * @return
	 */
	@Transactional(value = "transactionManager", propagation=Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
	public ResultEntity finishTransact(String trade_no, String serial_number, float money) {
		ResultEntity re = null;
		
		try{
			//获取该支付交易信息
			SpOrder order = soMapper.getSpOrderByOrderId(trade_no);
			
			String time = DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC);
			order.setPaidTime(time);
			order.setPaySerialNumber(serial_number);
			order.setPayState("Y");
			if(order.getDeliveryAddrId() > 0)
				order.setOrderState("2");
			else
				order.setOrderState("3");
			
			//支付成功后扣除积分
			if(order.getOrderPoint().intValue() > 0){
				EcMemberInfo member = emiMapper.selectByPrimaryKey(order.getMemberInfoId());
				if((member.getIntegral() - order.getOrderPoint().intValue()) > 0)
					member.setIntegral(member.getIntegral() - order.getOrderPoint().intValue());
				else
					member.setIntegral(0);
				
				emiMapper.updateByPrimaryKeySelective(member);
			}
			
			order.setEditTime(time);
			
			int rei = soMapper.updateByPrimaryKeySelective(order);
			
			if(rei > 0){
				
				//拼团订单  修改拼团参与表支付状态
				if("GROUP".equals(order.getAuditTime())){
					SpSpellGroupParticipate ssgp = ssgpMapper.selectByPrimaryKey(order.getAuditUserId());
					ssgp.setPayState("Y");
					ssgp.setEditTime(time);
					ssgpMapper.updateByPrimaryKeySelective(ssgp);
					
					//修改拼团活动参与人数
					SpSpellGroup group = ssgMapper.selectByPrimaryKey(ssgp.getSpellId());
					group.setEditTime(time);
					group.setNowSpellPeop(group.getNowSpellPeop() + 1);
					ssgMapper.updateByPrimaryKeySelective(group);
				}else if("LIMIT".equals(order.getAuditTime())){//抢购订单 修改抢购信息抢购人数信息
					SpLimitTimeShop slts = sltsMapper.selectByPrimaryKey(order.getAuditUserId());
					slts.setLimitNum(slts.getLimitNum() + 1);
					slts.setEditTime(time);
					sltsMapper.updateByPrimaryKeySelective(slts);
				}
				
				re = new ResultEntity("0");
			}else{
				re = new ResultEntity("-1", "操作失败！");
			}
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}
	
	/**
	 * 生成支付交易
	 * @param memberId 会员ID
	 * @param payMoney 支付金额
	 * @param ip 支付IP地址
	 * @return
	 */
	@Transactional(value = "transactionManager", propagation=Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
	public ResultEntity buildOrder(Integer memberId, Float allAmount, Float payMoney, String ip, String openid, String couponsId, 
			Integer addrId, List<Map<String, Object>> list, Integer storeId, String skuId, String skuAmount, String skuPrice, String tpn, String spellId, String limitTimeId, String orderPoint) {
		ResultEntity re = null;
		
		try{
			String orderId = null;
			
			//判断拼团情况下 该会员是否已生成过该拼团活动订单
			if(StringUtils.isNotEmpty(spellId)/* || StringUtils.isNotEmpty(limitTimeId)*/){
				SpOrderCriteria example = new SpOrderCriteria();
				List<String> states = new ArrayList<String>();
				states.add("6");states.add("7");states.add("8");
				if(StringUtils.isNotEmpty(spellId)){
					example.createCriteria().andMemberInfoIdEqualTo(memberId).andAuditUserIdEqualTo(Integer.parseInt(spellId)).andAuditTimeEqualTo("GROUP").andOrderStateNotIn(states).andIsDeleteEqualTo("N");
				}/*else{
					example.createCriteria().andMemberInfoIdEqualTo(memberId).andAuditUserIdEqualTo(Integer.parseInt(limitTimeId)).andAuditTimeEqualTo("LIMIT").andOrderStateNotIn(states).andIsDeleteEqualTo("N");
				}*/
				
				List<SpOrder> ods = soMapper.selectByExample(example);
				if(ods.size() > 0){
					orderId = ods.get(0).getOrderId();
				}
			}
			
	 		if(StringUtils.isEmpty(orderId)){
	 			
	 			//生成支付编号
				SimpleDateFormat formatter1=new SimpleDateFormat("yyyyMMdd");  
				String trade1=formatter1.format(new Date());
		        Date date1=formatter1.parse(trade1);
				Date date2=new Date();
		        long l = date2.getTime() - date1.getTime();
		        String trade2=String.valueOf(l);
		 		if(trade2.length()<8){
		 			for(int i=trade2.length();i<8;i++){
		 				trade2="0"+trade2;
		 			}
		 		}
		 		
	 			orderId = "CJWM" + trade1 + trade2;//生成订单
		 		
		 		/******************************数据库生成支付交易记录 begin*********************************/
	 			Format f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Calendar c = Calendar.getInstance();  
		        c.setTime(new Date());  
	 			
		 		SpOrder order = new SpOrder();
		 		String time = DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC);
		 		order.setOrderId(orderId);
		 		if(StringUtils.isNotEmpty(couponsId))
		 			order.setCouponsId(Integer.parseInt(couponsId));
		 		order.setDeliveryAddrId(addrId);
		 		order.setOrderState("1");
		 		order.setCreateTime(time);
		 		order.setPayState("N");
		 		order.setAllAmount(new BigDecimal(allAmount));
		 		order.setRealAmount(new BigDecimal(payMoney));
		 		order.setAddTime(time);
		 		order.setAddUserId(memberId);
		 		order.setMemberInfoId(memberId);
		 		order.setIpAddress(ip);
		 		if(StringUtils.isNotEmpty(orderPoint)){
		 			order.setOrderPoint(new BigDecimal(orderPoint));
		 		}
		 		
		 		c.add(Calendar.DATE, 7);
				order.setOrderLimitDate(f.format(c.getTime()));
				
		 		if(StringUtils.isNotEmpty(spellId)){
		 			order.setAuditUserId(Integer.parseInt(spellId));
		 			order.setAuditTime("GROUP");
		 		}
		 			
		 		if(StringUtils.isNotEmpty(limitTimeId)){
		 			order.setAuditUserId(Integer.parseInt(limitTimeId));
		 			order.setAuditTime("LIMIT");
		 			
		 			c.setTime(new Date());
					c.add(Calendar.MINUTE, 30);
					order.setOrderLimitDate(f.format(c.getTime()));
		 		}
		 		
		 		int rei = soMapper.insertSelective(order);
		 		/******************************数据库生成支付交易记录 end*********************************/
		 		
		 		if(rei > 0){
		 			//记录商品订单关联数据
		 			if(list.size() > 0){
		 				List<Integer> detailIds = new ArrayList<Integer>();
		 				
		 				for (Map<String, Object> map : list) {
		 					map.put("sku_amount", Integer.parseInt(map.get("sku_amount").toString()));
							map.put("store_id", storeId);
							map.put("memberId", memberId);
							map.put("order_id", orderId);
							detailIds.add((Integer) map.get("osc_detail_id"));
						}
		 				
		 				//锁定库存
		 				ssiMapper.batchUpdateAmount(list);
		 				
		 				rei = soMapper.batchInsertOrderSku(list);
		 				
		 				if(rei > 0){
		 					//清理购物车
		 					rei = ssiMapper.batchDelShopCartDetail(detailIds);
		 				}
		 			}else{
		 				Map<String, Object> param = new HashMap<String, Object>();
		 				param.put("store_id", storeId);
		 				param.put("memberId", memberId);
		 				param.put("order_id", orderId);
		 				param.put("sku_id", skuId);
		 				String promote_type_no = "NORMAL";
		 				if("1".equals(tpn))
		 					promote_type_no = "GROUP_BUY";
		 				else if("2".equals(tpn))
		 					promote_type_no = "LIMIT_BUY";
		 				param.put("promote_type_no", promote_type_no);
		 				param.put("sku_price", skuPrice);
		 				param.put("sku_fee", payMoney);
		 				param.put("sku_amount", skuAmount);
		 				
		 				//锁定库存
		 				SpSkuInfo sku = ssiMapper.selectByPrimaryKey(Integer.parseInt(skuId));
		 				sku.setLockAmountRest(sku.getLockAmountRest() + Integer.parseInt(skuAmount));
		 				sku.setStockAmountRest(sku.getStockAmountRest() - Integer.parseInt(skuAmount));
		 				ssiMapper.updateByPrimaryKeySelective(sku);
		 				
		 				rei = soMapper.insertOrderSku(param);
		 			}
		 			
		 			if(rei > 0){
		 				//生成微信公众号支付交易参数
				 		re = buildPayStr(orderId, payMoney, ip, openid);
				 		if(!"0".equals(re.getCode())){
				 			re.setData(orderId);
				 		}
		 			}else{
		 				re = new ResultEntity("-1", "记录订单商品信息失败！");
		 			}
		 		}else{
		 			re = new ResultEntity("-1", "生成订单失败！", orderId);
		 		}
	 		}else{
	 			//生成微信公众号支付交易参数
		 		re = buildPayStr(orderId, payMoney, ip, openid);
		 		if(!"0".equals(re.getCode())){
		 			re.setData(orderId);
		 		}
	 		}
	 		
	 		
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}
	
	/**
	 * 组织支付参数
	 * @param orderId 支付交易ID
	 * @param payMoney 支付金额 
	 * @param type 交易类型  1：购彩 2：充值
	 * @param ip 客户端IP
	 * @return
	 */
	public ResultEntity buildPayStr(String orderId, float payMoney, String ip, String openid) {
		ResultEntity re = null;
		String msg = "";
		try{
			/******************************微信支付签名数据返回 begin*********************************/
			int total_fee = (int) (payMoney * 100);//微信支付金额需转换成分 需为整数类型
			
			String nonceStr = WXPayUtil.generateUUID().toUpperCase();
			String body = "参境39度商城支付";
			String attach = "参境39度商城微信支付";
			String spbill_create_ip = ip;
			String notify_url = WechatConfig2.notify_url;
			String trade_type = WechatConfig2.JS_TRADE_TYPE;
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("appid", WechatConfig2.GZ_APPID);
			param.put("attach", attach);
			param.put("body", body);
			param.put("mch_id", WechatConfig2.GZ_MCHID);
			param.put("nonce_str", nonceStr);
			param.put("notify_url", notify_url);
			param.put("openid", openid);
			param.put("out_trade_no", orderId);
			param.put("spbill_create_ip", spbill_create_ip);
			param.put("total_fee", String.valueOf(total_fee));
			param.put("trade_type", trade_type);
			
			String[] signFields1 = new String[] { "appid", "attach", "body", "mch_id", "nonce_str", "notify_url", "openid", "out_trade_no", "spbill_create_ip", "total_fee", "trade_type" };
			
			String strA = SignatureUtil.orgSignSrc(signFields1, param);
			
			String sign = Md5.getMD5Str(strA+"&key="+WechatConfig2.GZ_MCHKEY).toUpperCase();//微信支付使用MD5加密
			
			param.put("sign", sign);
			
			String req_uri = "https://api.mch.weixin.qq.com/pay/unifiedorder";
			
			String xml = "<xml><appid>"+WechatConfig2.GZ_APPID+"</appid><attach>"+attach+"</attach><body>"+body+"</body><mch_id>"+WechatConfig2.GZ_MCHID+"</mch_id>" + 
					"<nonce_str>"+nonceStr+"</nonce_str><notify_url>"+notify_url+"</notify_url><openid>"+openid+"</openid>" + 
					"<out_trade_no>"+orderId+"</out_trade_no><spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>" + 
					"<total_fee>"+total_fee+"</total_fee><trade_type>"+trade_type+"</trade_type><sign>"+sign+"</sign></xml>";
   
				String req_uri_str = CommonUtilsEx.httpsRequest(req_uri,"POST",xml);
			System.out.println("统一下单Str：" + req_uri_str);
			Map json_map = CommonUtilsEx.doXMLParse(req_uri_str);
			System.out.println("统一下单Map：" + json_map);
			if("SUCCESS".equals(String.valueOf(json_map.get("return_code")))){
				String timeStamp = System.currentTimeMillis()+"";
				nonceStr = StringUtilsEx.RandomString(32).toUpperCase();
				String signType = "MD5";
				String pkg = "prepay_id="+json_map.get("prepay_id");
				
				Map<String, Object> prm = new HashMap<String, Object>();
				prm.put("appId", WechatConfig2.GZ_APPID);
				prm.put("timeStamp", timeStamp);
				prm.put("nonceStr", nonceStr);
				prm.put("signType", signType);
				prm.put("package", pkg);
				
				String[] signFields2 = new String[] { "appId", "timeStamp", "nonceStr", "package", "signType" };
				
				String strB = SignatureUtil.orgSignSrc(signFields2, prm);
				
				String sign1 = Md5.getMD5Str(strB+"&key="+WechatConfig2.GZ_MCHKEY).toUpperCase();//微信支付使用MD5加密
				
				prm.put("sign", sign1);
				prm.put("orderId", orderId);
				
				re = new ResultEntity(prm);
				
			}else{
				msg = String.valueOf(json_map.get("return_msg"));
				re = new ResultEntity("-1", msg);
			}
			/******************************微信支付签名数据返回 end*********************************/
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 根据订单号获取订单信息
	 * @param orderId
	 * @return
	 */
	public SpOrder getOrderByOrderId(String orderId) {
		return soMapper.getOrderByOrderId(orderId);
	}

	/**
	 * 获取个人订单信息
	 * @param memberId
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	public ResultEntity getOrderListByMemberId(Integer memberId, String orderState, Integer startIndex, Integer pageSize) {
		ResultEntity re = null;
		try{
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("memberId", memberId);
			param.put("orderState", orderState);
			param.put("startIndex", startIndex);
			param.put("pageSize", pageSize);
			
			//获取订单列表信息
			List<Map<String, Object>> orderList = soMapper.getOrderListByMemberIdWithPage(param);
			List<Map<String, Object>> skuList = null;
			for (Map<String, Object> order : orderList) {
				skuList = new ArrayList<Map<String,Object>>();
				//获取订单商品信息
				skuList = ssiMapper.getSkuListByOrderId(order.get("order_id"));
				order.put("skuList", skuList);
			}
			
			re = new ResultEntity(orderList);
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 个人提现申请
	 * @param memberId 会员ID
	 * @param money 提现金额
	 * @param type 提现方式 1：支付宝 2：微信 3：银行卡
	 * @param memberCardId 会员银行卡id 需走绑定银行卡流程 提现方式为银行卡时必传
	 * @param aliAcc 支付宝账号  提现方式为支付宝时必传
	 * @param aliRealName 支付宝账号实名认证的姓名  提现方式为支付宝时必传
	 * @param openId 微信openId 该方式暂不使用
	 * @param ip 客户端IP
	 * @return
	 */
	public ResultEntity addWithdrawalsApply(Integer memberId, Float money, String type, String memberCardId,
			String aliAcc, String aliRealName, String openId, String ip, String weixinAccount) {
		ResultEntity re = null;
		
		try{
			//生成提现编号
			SimpleDateFormat formatter1=new SimpleDateFormat("yyyyMMdd");  
			String trade1=formatter1.format(new Date());
	        Date date1=formatter1.parse(trade1);
			Date date2=new Date();
	        long l = date2.getTime() - date1.getTime();
	        String trade2=String.valueOf(l);
	 		if(trade2.length()<8){
	 			for(int i=trade2.length();i<8;i++){
	 				trade2="0"+trade2;
	 			}
	 		}
	 		
	 		String withdrawalNum = "CJTX" + trade1 + trade2;//提现编号
	 		String describe = "";//提现说明
	 		
	 		if("1".equals(type)){
	 			describe = "提现至支付宝";
	 		}else if("2".equals(type)){
	 			describe = "提现至微信";
	 		}else{
	 			describe = "提现至银行卡";
	 		}
	 		
	 		Date now = new Date();
	 		
	 		//会员余额暂扣，审核失败时返还余额，审核成功则流程结束
	 		EcMemberInfo member = emiMapper.selectByPrimaryKey(memberId);
	 		
	 		if(member.getAvailableBalance().subtract(new BigDecimal(money)).compareTo(new BigDecimal(0)) == -1){
	 			re = new ResultEntity("-1", "余额不足！");
	 			return re;
	 		}
	 		
	 		member.setAvailableBalance(member.getAvailableBalance().subtract(new BigDecimal(money)));
	 		emiMapper.updateByPrimaryKeySelective(member);
	 		
	 		//获取提现手续费
			List<Map<String, Object>> list = cMapper.getSysCode("tx_rate");
			
			BigDecimal txRate = new BigDecimal(0);
			if(list.size() > 0){
				txRate = new BigDecimal(String.valueOf(list.get(0).get("code_value")));
			}
			
			money = money * (new BigDecimal(1).subtract(txRate)).floatValue();
			
			//新增提现申请记录
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("memberId", memberId);
			param.put("withdrawalAmount", money);
			param.put("withdrawalNum", withdrawalNum);
			/*param.put("weixinAccount", openId);*/
			param.put("weixinAccount", weixinAccount);
			param.put("zfbAccount", aliAcc);
			param.put("withdrawalDescribe", describe);
			param.put("merchantsIp", ip);
			param.put("addTime", DateUtilsEx.formatToString(now, "yyyy-MM-dd HH:mm:ss"));
			
			int rei = soMapper.addWithdrawalsApply(param);
			
			//新增提现账单记录
			if(rei > 0){
				re = new ResultEntity("0");
			}else{
				re = new ResultEntity("-1", "申请失败！");
			}
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 获取订单取消原因
	 * @return
	 */
	public List<Map<String, Object>> getOrderCancelReason() {
		return soMapper.getOrderCancelReason();
	}

	/**
	 * 取消订单 
	 * @param memberId 取消人ID
	 * @param orderId 订单号
	 * @param reasonId 取消原因ID
	 * @param notes 取消原因描述
	 * @return
	 */
	public ResultEntity cancelOrder(Integer memberId, String orderId, Integer reasonId, String notes) {
		ResultEntity re = null;
		try{
			
			SpOrder order = soMapper.getOrderByOrderId(orderId);
			order.setOrderCancelReasonId(reasonId);
			order.setOrderCancelNotes(notes);
			order.setOrderState("8");
			order.setOrderCancelTime(DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC));;
			
			int res = soMapper.updateByPrimaryKeySelective(order);
			
			if(res > 0){
				//解锁库存
				SpOrderSkuCriteria emp = new SpOrderSkuCriteria();
				emp.createCriteria().andOrderIdEqualTo(orderId);
				List<SpOrderSku> toslist = sosMapper.selectByExample(emp);
				for (SpOrderSku tos : toslist) {
					SpSkuInfo tsi = ssiMapper.selectByPrimaryKey(tos.getSkuId());
					tsi.setLockAmountRest(tsi.getLockAmountRest() - tos.getSkuAccount().intValue());
					tsi.setStockAmountRest(tsi.getStockAmountRest() + tos.getSkuAccount().intValue());
					int ri = ssiMapper.updateByPrimaryKeySelective(tsi);
					if(ri == 0){
						re = new ResultEntity("-1", "锁定库存修改失败！");
						return re;
					}
				}
				
				re = new ResultEntity("0");
			}else
				re = new ResultEntity("-1", "订单取消失败！");
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 
	 * @param memberId
	 * @param openid
	 * @param orderId
	 * @return
	 */
	public ResultEntity buildOrderPay(Integer memberId, String openid, String orderId, String ip) {
		ResultEntity re = null;
		
		try{
			//获取订单基本信息
			SpOrder order = soMapper.getOrderByOrderId(orderId);
			
			//订单直接支付判断积分是否足够
			if(order.getOrderPoint().intValue() > 0){
				//获取会员当前剩余积分
				EcMemberInfo member = emiMapper.selectByPrimaryKey(order.getMemberInfoId());
				
				if(member.getIntegral() < order.getOrderPoint().intValue()){
					re = new ResultEntity("-1", "该订单您已选择积分抵扣，目前您的积分不足，您可重新下单购买！");
					return re;
				}
				
			}
			
			//生成微信公众号支付交易参数
	 		re = buildPayStr(orderId, order.getRealAmount().floatValue(), ip, openid);
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 确认收货
	 * @param memberId
	 * @param orderId
	 * @return
	 */
	@Transactional(value = "transactionManager", propagation=Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
	public ResultEntity takeOrder(Integer memberId, String orderId) {
		ResultEntity re = null;
		
		try{
			//获取订单基本信息
			SpOrder order = soMapper.getOrderByOrderId(orderId);
			
			String time = DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC);
			
			order.setOrderState("4");
			order.setOrderCheckTime(time);
			order.setEditTime(time);
			order.setEditUserId(memberId);
			
			int rei = soMapper.updateByPrimaryKeySelective(order);
			
			if(rei > 0){
				//计算积分并发放积分
				int score = 0;
				String msg = "";
				//首先判断订单消费金额是否达到购满金额积分赠送标准
				List<Map<String, Object>> list = cMapper.getSysCode("score_rule");
				for (Map<String, Object> rule : list) {
					if(order.getRealAmount().compareTo(new BigDecimal(rule.get("code_no").toString())) >= 0){
						score = Integer.parseInt(rule.get("code_value").toString());
						msg = "购物满" + rule.get("code_no") + "元，赠送" + score + "积分";
//						break;
					}
				}
				
				if(score == 0){
					//根据购买商品的赠送积分属性 计算积分
					List<Map<String, Object>> skuList = ssiMapper.getSkuListByOrderId(orderId);
					for (Map<String, Object> map : skuList) {
						
						int cnt = new BigDecimal(map.get("sku_account").toString()).intValue();//商品数量
						int twMoney = new BigDecimal(map.get("tw_money").toString()).intValue();//商品赠送积分属性
						
						score += (twMoney * cnt);
					}
					
					msg = "购买商品，赠送" + score + "积分";
				}
				
				//开始发放积分
				if(score > 0){
					//记录积分收益明细
					EcIncomeDetail eid = new EcIncomeDetail();
					eid.setIncomeMoney(new BigDecimal(score));
					eid.setMemberInfoId(memberId);
					eid.setAddUserId(memberId);
					eid.setIncomeType("2");
					eid.setAddTime(DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC));
					eidMapper.insertSelective(eid);
					
					//修改会员积分信息
					EcMemberInfo member = emiMapper.selectByPrimaryKey(memberId);
					member.setIntegral(member.getIntegral() + score);
					member.setEditTime(DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC));
					emiMapper.updateByPrimaryKeySelective(member);
				}
				
				re = new ResultEntity("0");
			}else{
				re = new ResultEntity("-1", "确认失败！");
			}
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 个人收益列表
	 * @param memberId
	 * @param startTime
	 * @param endTime
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	public ResultEntity getIncomeListByMemberId(Integer memberId, String incomeType, String startTime, String endTime, Integer startIndex,
			Integer pageSize) {
		ResultEntity re = null;
		
		try{
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("memberId", memberId);
			param.put("startTime", startTime);
			param.put("endTime", endTime);
			param.put("incomeType", incomeType);
			param.put("startIndex", startIndex);
			param.put("pageSize", pageSize);
			
			List<Map<String, Object>> list = soMapper.getIncomeListByMemberIdWithPage(param);
			
			re = new ResultEntity(list);
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 获取销售统计
	 * @param memberId
	 * @return
	 */
	public Map<String, Object> getSaleCount(Integer memberId) {
		return soMapper.getSaleCount(memberId);
	}

	/**
	 * 销售统计列表
	 * @param memberId
	 * @param startTime
	 * @param endTime
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	public ResultEntity getSaleListByMemberId(Integer memberId, String startTime, String endTime, Integer startIndex,
			Integer pageSize) {
		ResultEntity re = null;
		
		try{
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("memberId", memberId);
			param.put("startTime", startTime);
			param.put("endTime", endTime);
			param.put("startIndex", startIndex);
			param.put("pageSize", pageSize);
			
			List<Map<String, Object>> list = soMapper.getSaleListByMemberIdWithPage(param);
			
			re = new ResultEntity(list);
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 门店销售订单列表
	 * @param memberId
	 * @param orderState
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	public ResultEntity getSaleOrderListByMemberId(Integer memberId, String orderState, Integer startIndex,
			Integer pageSize) {
		ResultEntity re = null;
		try{
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("memberId", memberId);
			param.put("orderState", orderState);
			param.put("startIndex", startIndex);
			param.put("pageSize", pageSize);
			
			//获取订单列表信息
			List<Map<String, Object>> orderList = soMapper.getSaleOrderListByMemberIdWithPage(param);
			List<Map<String, Object>> skuList = null;
			for (Map<String, Object> order : orderList) {
				skuList = new ArrayList<Map<String,Object>>();
				//获取订单商品信息
				skuList = ssiMapper.getSkuListByOrderId(order.get("order_id"));
				order.put("skuList", skuList);
			}
			
			re = new ResultEntity(orderList);
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 获取订单详情
	 * @param orderId
	 * @return
	 */
	public Map<String, Object> getOrderDetailByOrderId(String orderId) {
		Map<String, Object> rem = new HashMap<String, Object>();
		
		//获取订单基本信息
		SpOrder order = soMapper.getOrderByOrderId(orderId);
		rem.put("order", order);
		
		//获取订单商品信息
		List<Map<String, Object>> skuList = ssiMapper.getSkuListByOrderId(orderId);
		for (Map<String, Object> map : skuList) {
			map.put("sku_account", new BigDecimal(map.get("sku_account").toString()).intValue());
		}
		rem.put("skuList", skuList);
		
		//获取收货地址信息
		Map<String, Object> address = emiMapper.getAddressByAddrId(order.getDeliveryAddrId());
		rem.put("address", address);
		
		//获取消费门店信息
		if(skuList.size() > 0){
			rem.put("storeName", skuList.get(0).get("store_name"));
		}
		
		return rem;
	}

	/**
	 * 确认发货
	 * @param memberId
	 * @param orderId
	 * @return
	 */
	public ResultEntity confirmOrder(Integer memberId, String orderId) {
		ResultEntity re = null;
		try{
			
			SpOrder order = soMapper.getOrderByOrderId(orderId);
			
			order.setOrderState("3");
			order.setEditTime(DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC));
			order.setEditUserId(memberId);
			
			int rei = soMapper.updateByPrimaryKeySelective(order);
			
			if(rei > 0){
				re = new ResultEntity("0");
			}else{
				re = new ResultEntity("-1", "操作失败！");
			}
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 修改到期未支付订单状态
	 * @return
	 */
	public ResultEntity updateNotPayLimitOrderState() {
		ResultEntity re = null;
		try{
			
			SpOrder record = new SpOrder();
			record.setOrderCancelReasonId(0);
			record.setOrderCancelNotes("未支付订单超时取消");
			record.setOrderState("8");
			record.setEditTime(DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC));
			
			SpOrderCriteria example = new SpOrderCriteria();
			example.createCriteria().andOrderStateEqualTo("1").andOrderLimitDateLessThan(DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC));
			soMapper.updateByExampleSelective(record, example);
			
			re = new ResultEntity("0");
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 订单到期自动确认收货
	 * @return
	 */
	public ResultEntity updateOrderTakeState() {
		ResultEntity re = null;
		try{
			
			soMapper.updateOrderTakeState();
			
			re = new ResultEntity("0");
			
		}catch(Exception e){
			e.printStackTrace();
			re = new ResultEntity("-1", "系统异常！");
		}
		
		return re;
	}

	/**
	 * 获取会员本次交易可使用积分
	 * @param memberId
	 * @param payMoney
	 * @return
	 */
	public Map<String, Object> getScoreInfoByTransact(Integer memberId, String payMoney) {
		// 获取会员基本信息
		EcMemberInfo member = emiMapper.selectByPrimaryKey(memberId);
		
		int integral = member.getIntegral();//会员可用积分
		int usedScore = 0;//可抵扣积分
		
		BigDecimal money = new BigDecimal(payMoney);
		BigDecimal dkMoney = new BigDecimal("0");
		BigDecimal scoreMoney = money;
		String msg = "";
		
		//获取使用积分抵扣标准
		List<Map<String, Object>> list = cMapper.getSysCode("used_score_rule");
		
		for (Map<String, Object> rule : list) {
			if(money.compareTo(new BigDecimal(rule.get("code_no").toString())) >= 0){
				usedScore = Integer.parseInt(rule.get("code_value").toString());
				msg = "购物满" + rule.get("code_no") + "元，可抵扣" + usedScore + "积分";
				System.out.println(msg);
//				break;
			}
		}
		
		if(usedScore > 0){
			if(integral < usedScore){//如果当前可用积分小于可抵扣积分 则可抵扣积分重新赋值为会员当前剩余积分
				usedScore = integral;
				msg = "本次交易，实际抵扣" + usedScore + "积分";
				System.out.println(msg);
			}
		}
		
		if(usedScore > 0){
			dkMoney = new BigDecimal(usedScore);
			scoreMoney = money.subtract(dkMoney);
		}
		
		Map<String, Object> rem = new HashMap<String, Object>();
		rem.put("integral", integral);
		rem.put("usedScore", usedScore);
		rem.put("dkMoney", dkMoney);
		rem.put("scoreMoney", scoreMoney);
		
		return rem;
	}


}
